package com.calvin.study.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import com.calvin.study.entity.User;

public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private  RestTemplate restTemplate;
	@Value("${sso.server.url}")
	private String ssoUrl ;
	@Value("${sso.server.checktoken.url}")
	private String ssoCheckTokenUrl;


    // true: 放行    false: 拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断客户端到底有没有带 jsessionid过来
        HttpSession session = request.getSession(false);
        if(session!=null && null != session.getAttribute("loginUser")){
        	System.out.println(session.getAttribute("loginUser"));
            return true;
        }

        // 判断是否有token，sso-server有没有颁发token给我
        String token = request.getParameter("token");
        
        if(token!=null){
            // 判断token有效性
            String reqUrl=ssoCheckTokenUrl  + "?token=" + token;
            // java.net.URLConnection请求
            ResponseEntity<User> resp = restTemplate.getForEntity(reqUrl , User.class);
            User user  = resp.getBody();
            if(null != user) {
                // 为了后续能够免登录，要创建session对象
                request.getSession().setAttribute("loginUser",user);
                return true;
            }
        }
        // 发现并没有sessionid   一旦后面登录成功了，还需要返回给用户受保护的资源  url=www.user.com:8081/user/wel
        response.sendRedirect(ssoUrl + "?url=http://user.calvin.com:8081/user/index");
        return false;
    }
}
